import React, { useState, useEffect } from 'react';
import { Card, Table, Button, Input, Select, Tag, Space, Modal, Upload, Tooltip, Menu, Dropdown, Badge, Form, DatePicker, message } from 'antd';
import type { MenuProps } from 'antd';
import { 
  PlusOutlined, 
  UploadOutlined, 
  FilterOutlined, 
  SearchOutlined, 
  FileTextOutlined, 
  FolderOutlined,
  MoreOutlined,
  EditOutlined,
  DeleteOutlined,
  DownloadOutlined,
  ShareAltOutlined,
  ExportOutlined,
  ImportOutlined,
  HomeOutlined,
  InboxOutlined
} from '@ant-design/icons';
import DocumentDetails from './DocumentDetails';
import { useDocumentStore, Document } from '../../stores/documentStore';
import { Key } from 'react';

const { Search } = Input;
const { Option } = Select;
const { RangePicker } = DatePicker;

interface FolderType {
  id: string;
  name: string;
  parentId: string | null;
}

const DocumentLibrary: React.FC = () => {
  const { documents, folders, loading, fetchDocuments, selectedDocument, selectDocument } = useDocumentStore();
  const [searchText, setSearchText] = useState('');
  const [showDetails, setShowDetails] = useState(false);
  const [statusFilter, setStatusFilter] = useState<string[]>([]);
  const [typeFilter, setTypeFilter] = useState<string[]>([]);
  const [dateRange, setDateRange] = useState<[string, string] | null>(null);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [isCreatingFolder, setIsCreatingFolder] = useState(false);
  const [uploadModalVisible, setUploadModalVisible] = useState(false);
  
  useEffect(() => {
    fetchDocuments();
  }, [fetchDocuments]);
  
  // 处理搜索
  const handleSearch = (value: string) => {
    setSearchText(value);
  };
  
  // 处理状态筛选
  const handleStatusFilter = (value: string[]) => {
    setStatusFilter(value);
  };
  
  // 处理类型筛选
  const handleTypeFilter = (value: string[]) => {
    setTypeFilter(value);
  };
  
  // 处理日期范围筛选
  const handleDateRangeChange = (dates: any, dateStrings: [string, string]) => {
    setDateRange(dates ? dateStrings : null);
  };
  
  // 处理表格行选择
  const onSelectChange = (selectedKeys: React.Key[]) => {
    setSelectedRowKeys(selectedKeys);
  };
  
  // 处理查看文档详情
  const handleViewDocument = (document: Document) => {
    selectDocument(document);
    setShowDetails(true);
  };
  
  // 处理关闭文档详情
  const handleCloseDetails = () => {
    setShowDetails(false);
    selectDocument(null);
  };
  
  // 处理创建文件夹
  const handleCreateFolder = () => {
    setIsCreatingFolder(true);
  };
  
  // 提交创建文件夹
  const handleSubmitCreateFolder = (values: any) => {
    message.success(`成功创建文件夹：${values.folderName}`);
    setIsCreatingFolder(false);
    fetchDocuments();
  };
  
  // 处理上传文档
  const handleUploadDocument = () => {
    setUploadModalVisible(true);
  };
  
  // 处理删除选中项
  const handleDeleteSelected = () => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除选中的 ${selectedRowKeys.length} 个项目吗？`,
      onOk() {
        message.success(`成功删除 ${selectedRowKeys.length} 个项目`);
        setSelectedRowKeys([]);
        fetchDocuments();
      },
    });
  };
  
  // 获取文件类型颜色
  const getTypeColor = (type: string) => {
    switch (type) {
      case 'PDF':
        return '#f5222d';
      case 'Word':
        return '#1890ff';
      case 'Excel':
        return '#52c41a';
      case 'PPT':
        return '#fa8c16';
      case 'Text':
        return '#722ed1';
      default:
        return '#d9d9d9';
    }
  };
  
  // 过滤文档
  const filteredDocuments = documents.filter((doc: Document) => {
    // 搜索过滤
    const matchesSearch = doc.name.toLowerCase().includes(searchText.toLowerCase()) ||
                          doc.tags.some((tag: string) => tag.toLowerCase().includes(searchText.toLowerCase()));
    
    // 状态过滤
    const matchesStatus = statusFilter.length === 0 || statusFilter.includes(doc.status);
    
    // 类型过滤
    const matchesType = typeFilter.length === 0 || typeFilter.includes(doc.type);
    
    // 日期范围过滤
    const matchesDateRange = !dateRange || 
                            (new Date(doc.updateTime) >= new Date(dateRange[0]) && 
                             new Date(doc.updateTime) <= new Date(dateRange[1]));
    
    return matchesSearch && matchesStatus && matchesType && matchesDateRange;
  });
  
  // 渲染当前路径面包屑
  const renderBreadcrumb = () => {
    // 获取当前文件夹路径
    const folderPath: Array<{id: string; name: string}> = []; // 实际项目中需根据文件夹ID获取路径
    
    return (
      <div style={{ display: 'flex', alignItems: 'center' }}>
        <Button 
          type="text" 
          icon={<HomeOutlined />}
          style={{ padding: '0 4px' }}
        >
          根目录
        </Button>
        {folderPath.map((folder, index) => (
          <React.Fragment key={folder.id}>
            <span>/</span>
            <Button 
              type="text"
              style={{ padding: '0 4px' }}
            >
              {folder.name}
            </Button>
          </React.Fragment>
        ))}
      </div>
    );
  };

  // 表格列配置
  const columns = [
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
      sorter: (a: Document, b: Document) => a.name.localeCompare(b.name),
      render: (text: string, record: Document) => (
        <Space>
          <FileTextOutlined style={{ color: getTypeColor(record.type) }} />
          <a onClick={() => handleViewDocument(record)}>{text}</a>
          {record.tags.includes('重要') && <Badge color="red" />}
        </Space>
      ),
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      filters: [
        { text: 'PDF', value: 'PDF' },
        { text: 'Word', value: 'Word' },
        { text: 'Excel', value: 'Excel' },
        { text: 'PPT', value: 'PPT' },
        { text: 'Text', value: 'Text' },
      ],
      onFilter: (value: boolean | Key, record: Document) => record.type === value,
      render: (type: string) => <Tag color={getTypeColor(type)}>{type}</Tag>,
    },
    {
      title: '大小',
      dataIndex: 'size',
      key: 'size',
      sorter: (a: Document, b: Document) => {
        const aSize = parseInt(a.size);
        const bSize = parseInt(b.size);
        return aSize - bSize;
      },
    },
    {
      title: '创建者',
      dataIndex: 'creator',
      key: 'creator',
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      key: 'updateTime',
      sorter: (a: Document, b: Document) => new Date(a.updateTime).getTime() - new Date(b.updateTime).getTime(),
      defaultSortOrder: 'descend' as const,
      render: (date: string) => new Date(date).toLocaleDateString(),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      filters: [
        { text: '草稿', value: '草稿' },
        { text: '已发布', value: '已发布' },
        { text: '已归档', value: '已归档' },
      ],
      onFilter: (value: boolean | Key, record: Document) => record.status === value,
      render: (status: string) => (
        <Tag color={
          status === '已发布' ? 'green' : 
          status === '草稿' ? 'orange' : 
          'default'
        }>
          {status}
        </Tag>
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: Document) => {
        const items: MenuProps['items'] = [
          {
            key: 'view',
            label: '查看',
            icon: <FileTextOutlined />,
            onClick: () => handleViewDocument(record)
          },
          {
            key: 'download',
            label: '下载',
            icon: <DownloadOutlined />
          },
          {
            key: 'edit',
            label: '编辑',
            icon: <EditOutlined />
          },
          {
            key: 'delete',
            label: '删除',
            icon: <DeleteOutlined />,
            danger: true,
            onClick: () => {
              Modal.confirm({
                title: '确认删除',
                content: '确定要删除此文档吗？此操作不可恢复。',
                okText: '删除',
                okType: 'danger',
                cancelText: '取消',
                onOk: () => {
                  message.success('文档已删除');
                  fetchDocuments();
                }
              });
            }
          }
        ];

        return (
          <Space>
            <Button 
              type="text" 
              icon={<FileTextOutlined />} 
              onClick={() => handleViewDocument(record)}
            >
              查看
            </Button>
            <Dropdown menu={{ items }}>
              <Button type="text" icon={<MoreOutlined />} />
            </Dropdown>
          </Space>
        );
      }
    },
  ];
  
  return (
    <div>
      <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between' }}>
        <Space>
          <Button 
            type="primary" 
            icon={<PlusOutlined />} 
            onClick={handleCreateFolder}
          >
            新建文件夹
          </Button>
          <Button 
            icon={<UploadOutlined />} 
            onClick={handleUploadDocument}
          >
            上传文档
          </Button>
          {selectedRowKeys.length > 0 && (
            <Button 
              danger 
              icon={<DeleteOutlined />} 
              onClick={handleDeleteSelected}
            >
              删除选中
            </Button>
          )}
        </Space>
        
        <Space>
          <Search
            placeholder="搜索文件名或标签"
            onSearch={handleSearch}
            style={{ width: 250 }}
          />
          <Select 
            mode="multiple" 
            placeholder="文件类型" 
            style={{ width: 150 }}
            onChange={handleTypeFilter}
          >
            <Option value="PDF">PDF</Option>
            <Option value="Word">Word</Option>
            <Option value="Excel">Excel</Option>
            <Option value="PPT">PPT</Option>
            <Option value="Text">Text</Option>
          </Select>
          <Select 
            mode="multiple" 
            placeholder="状态" 
            style={{ width: 150 }}
            onChange={handleStatusFilter}
          >
            <Option value="草稿">草稿</Option>
            <Option value="已发布">已发布</Option>
            <Option value="已归档">已归档</Option>
          </Select>
          <RangePicker onChange={handleDateRangeChange} />
        </Space>
      </div>
      
      {/* 面包屑导航 */}
      <div style={{ marginBottom: 16 }}>
        {renderBreadcrumb()}
      </div>
      
      {/* 文件夹列表 */}
      {folders.length > 0 && (
        <div style={{ marginBottom: 16 }}>
          <h4 style={{ marginBottom: 12 }}>文件夹</h4>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 16 }}>
            {folders.map(folder => (
              <Card 
                key={folder.id}
                hoverable
                style={{ width: 180 }}
                onClick={() => {/* 处理文件夹点击 */}}
              >
                <div style={{ textAlign: 'center' }}>
                  <FolderOutlined style={{ fontSize: 32, color: '#fadb14' }} />
                  <p style={{ marginTop: 8 }}>{folder.name}</p>
                </div>
              </Card>
            ))}
          </div>
        </div>
      )}
      
      <Table
        columns={columns}
        dataSource={filteredDocuments}
        rowKey="id"
        pagination={{ pageSize: 10 }}
        loading={loading}
        rowSelection={{
          selectedRowKeys,
          onChange: onSelectChange,
        }}
      />
      
      {/* 创建文件夹弹窗 */}
      <Modal
        title="新建文件夹"
        open={isCreatingFolder}
        onOk={() => {
          Form.useForm()[0].validateFields().then(values => {
            handleSubmitCreateFolder(values);
          });
        }}
        onCancel={() => setIsCreatingFolder(false)}
      >
        <Form layout="vertical">
          <Form.Item
            name="folderName"
            label="文件夹名称"
            rules={[{ required: true, message: '请输入文件夹名称' }]}
          >
            <Input placeholder="请输入文件夹名称" />
          </Form.Item>
        </Form>
      </Modal>
      
      {/* 上传文档弹窗 */}
      <Modal
        title="上传文档"
        open={uploadModalVisible}
        footer={null}
        onCancel={() => setUploadModalVisible(false)}
      >
        <Upload.Dragger
          multiple
          listType="picture"
          action="/api/upload" // 实际项目中替换为真实上传接口
          onChange={(info) => {
            if (info.file.status === 'done') {
              message.success(`${info.file.name} 上传成功`);
              // 上传成功后刷新文档列表
              fetchDocuments();
            } else if (info.file.status === 'error') {
              message.error(`${info.file.name} 上传失败`);
            }
          }}
        >
          <p className="ant-upload-drag-icon">
            <InboxOutlined />
          </p>
          <p className="ant-upload-text">点击或拖拽文件到此区域上传</p>
          <p className="ant-upload-hint">支持单个或批量上传</p>
        </Upload.Dragger>
      </Modal>
      
      {/* 文档详情 */}
      {showDetails && (
        <DocumentDetails
          document={selectedDocument}
          onClose={handleCloseDetails}
        />
      )}
    </div>
  );
};

export default DocumentLibrary; 